<template>
  <view>
      <view>
        <view v-show="isTip" @touchmove.stop.prevent="stopSlide">
          <view class="mask" @click="isTip=false"></view>
          <view class="tip">点击右上角分享符，分享有分销提成 ↑</view>
        </view>
      </view>
      <view class="nav" v-if="showVideo">
          <view class="list">
              <block v-for="(item, index) in goodsData" :key="index">
                  <view :class="'itemD'" v-if="curD>0&&index==0" @tap="xunT"><<</view>
                  <view :class="'item ' + clas[index]" :data-index="index" @tap="xun">{{ item.title }}</view>
                  <view :class="'itemD'" v-if="goodsDataAll.length>6&&index>=4" @tap="xunD">>></view>
              </block>
          </view>
      </view>
      <scroll-view :scroll-Y="true" :scroll-X="false">
          <swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration" v-if="!hasUrl||showVideo" :current="current">
              <block v-for="(item, index) in goods.productPics" :key="index">
                  <swiper-item :data-id="item">
                      <image mode="scaleToFill" :src="item.productPic" v-if="item.isVideo == 0" @tap="toDetail" :id="goods.productDetail"/>
                      <video
                          mode="scaleToFill"
                          :src="item.productPic"
                          v-if="item.isVideo==1&&showVideo"
                          class="media"
                          :show-center-play-btn="true"
                          :enable-play-gesture="true"
                          :display="showVideo"
                          controls
                          loop
                      />
                  </swiper-item>
              </block>
          </swiper>
          <view class="info" v-if="!hasUrl">
              <text>{{ goods.productDesc }}</text>
          </view>
          <view class="infoD" v-if="hasUrl">
              <iframe src="" id="iFrame" width="100%" height="100%" frameborder="0"></iframe>
          </view>
      </scroll-view>      
  </view>
</template>

<script>
var config = require('../../config.js');
var http = require('../../utils/httpHelper.js');
var util = require('../../utils/util.js');
import wx from 'weixin-js-sdk';
export default {
  data() {
      return {
          //是否自动切换
          current: 0,
          //滑动时间
          clas: ['action'],
          goodsData: [],
          goodsDataAll: [],
          curD: 0,
          userInfo: {},
          isLogin: false,
          indicatorDots: true,
          //是否显示面板指示点
          autoplay: false,
          //是否自动切换
          interval: 5000,
          //自动切换时间
          duration: 1000,
          //滑动时间
          buyCount: 1,

          goods: {
              productPics: [],
              isVideo: 0,
              productTitle: '',
              productPrice: '',
              productDiscount: '',
              labelNames: '',
              productDesc: '',
              productDetail: ''
          },

          buyCount: '1',
          productPics: [],
          productVids: [],
          showVideo: false,
          isTip: false,
          hasUrl: false
      };
  },
  onLoad: function (options) {
      var that = this;        
      let userInfo = uni.getStorageSync('user');
      if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
          that.setData({
              isLogin: true,
              userInfo: userInfo
          });
      } else {
          uni.setStorageSync('inviteId', options.inviteId);
      }
      var id = options.id;
      that.getBannerInfo(id);        
      setTimeout(()=>{
          this.share();
      },6000)
  },
  onShow: function () {
      let userInfo = uni.getStorageSync('user');
      if (userInfo != null && userInfo != undefined && userInfo != {} && userInfo != '') {
          this.setData({
              isLogin: true,
              userInfo: userInfo
          });
      }
  },  
  methods: {
      xun: function (e) {
          var index = e.currentTarget.dataset.index;
          var data = [];
          data[index] = 'action';
          this.setData({
              clas: data
          });
          var showindex = this.curD*5+index;
          this.setData({
              current: showindex
          });
      },
      xunT: function (e) {
          var len = this.goodsDataAll.length;
          this.curD = this.curD-1;
          var start = this.curD*5;
          var end = (this.curD+1)*5;            
          if (start<=0) {
            this.setData({
              curD: 0,
              current: this.current%5,
              goodsData: this.goodsDataAll.slice(0,5)
            });
            return;
          }
          this.setData({
              current: this.current-5,
              goodsData: this.goodsDataAll.slice(start,end)
          });
      },
      xunD: function (e) {           
          var len = this.goodsDataAll.length;
          this.curD = this.curD+1;
          var start = this.curD*5;
          var end = (this.curD+1)*5;            
          if (start>=len) {
            this.setData({
              curD: 0,
              current: this.current%5,
              goodsData: this.goodsDataAll.slice(0,5)
            });
            return;
          }
          if (end>len) {
            end = len;
          }
          this.setData({
              current: this.current+5,
              goodsData: this.goodsDataAll.slice(start,end)
          });
      },
      toDetail: function (e) {
        window.location.href = e.currentTarget.id;
      },        
      getBannerInfo: function (id) {
          var curUserId = 0;
          if (this.userInfo.userId) {
            curUserId = this.userInfo.userId;
          }
          var that = this;
          var data = {
              id: id,
              userId: curUserId
          };
          http.httpGet(config.clubApi.getBannerInfo, data, function (res) {
              if (res.code == '200') {
                  var goods = res.data;
                  if (goods.productDetail) {
                    let head = goods.productDetail.slice(0, 24);
                    if (head === 'https://mp.weixin.qq.com') {// 是微信公众号文章
                        that.getURL(goods.productDetail);
                        that.hasUrl = true;
                    }
                  }
                  var goodPics = [];
                  var goodVids = [];
                  var goodsDataAll = [];
                  var index = 1;
                  goods.bannerPics.forEach((item) => {
                    if (item.isVideo==0) {
                      goodPics.push(item);
                    }else {
                      goodVids.push(item);
                      goodsDataAll.push({id:item.id, title:'第'+index+'节'});
                      index++;
                    }
                  })
                  goods.productPics = goodPics;
                  that.productVids = goodVids;
                  that.productPics= goodPics;
                  that.setData({
                      goods: goods
                  });
                  that.setData({
                      goodsDataAll: goodsDataAll,
                      goodsData: goodsDataAll.length>5?goodsDataAll.slice(0,5):goodsDataAll
                  });
              }
          });
      },
      getURL(url) {
          let realurl = 'http://121.41.116.2:8080/' + url;
          let that = this;            
          uni.request({
              type: 'get',
              url: realurl,
              header: {
                  'Access-Control-Allow-Origin': '*'
              },
              success: function (response) {
                  let html = response.data;
                  html = html.replace(/data-src/g, "src")
                      .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/g, '')
                      .replace(/https/g, 'http');
                  //根据微信传回的html中的特殊路径data-src转为src等
                  let html_src = html;
                  let iframe = document.getElementById('iFrame');
                  iframe.src = html_src;
                  //这时候就成功拿到了微信公众号，这个html_src是个静态网页
                  let doc = iframe.contentDocument || iframe.document;
                  //添加meta展示图片不加这个图片出不来
                  let htmlArr = html_src.split('</head>');
                  let html_src_add = htmlArr[0]+'<meta name="referrer" content="never"></head>'+htmlArr[1]
                  let backgroundUrlReg = /url[(]&quot;(\S*)&quot;/g;
                  //获取背景图
                  let backgroundImgs = html_src_add.match(backgroundUrlReg);
                  if (backgroundImgs&&backgroundImgs.length) {
                    backgroundImgs.forEach(item => {
                      let url = item.replace(/url[(]&quot;/g, '').replace(/&quot;/g, '');
                      let img = document.createElement('img');
                      img.src = url;
                      doc.querySelector("body").appendChild(img);
                    });
                  }
                  //配置无效img绕过背景图片路径限制
                  doc.write(html_src_add);
                  // 将静态页面写入iframe中
                  setTimeout(() => {
                    that.height = doc.documentElement.scrollHeight;
                  }, 30000);
                  //通过延时获取文档高度赋值Iframe去除滚动条，根据实际情况增加延时时间
                  doc.getElementById("js_content").style.visibility = "visible";
                  doc.getElementById("js_content").style.opacity = 1;
              },
              error: function (err) {
                  console.log(err);
                  Toast('好像出错了...');
              }
          });
      },      
      getSignUrl(){
          var signLink = ''
          var ua = navigator.userAgent.toLowerCase();
          if (/iphone|ipad|ipod/.test(ua)) {              
              signLink = 'http://jkhmzw.shudingkj.com/pages/detailb/index?id='+this.goods.id+'&inviteId='+this.userInfo.userId;
          } else {
              signLink = location.href
          }
          return signLink;
      },
      stopSlide() {
        return;
      },      
      share() {          
        var goods = this.goods;
        var curUrl = this.getSignUrl();
        const jsApiList=[
          'checkJsApi', //检测接口权限	
          'updateTimelineShareData',
          'updateAppMessageShareData',
          'openLocation'
        ];
        //这是后端写的接口，需要用后端返回内容配置微信分享的参数
        uni.request({
          method: 'GET',
          url: config.BASE_URL + '/auth/getWXInterface',
          data: {
            url:curUrl,
            appid:config.APPID
          },
          header: {
              'U-TOKEN': uni.getStorageSync('user') ? uni.getStorageSync('user').token : '/pages/detail/index',
              "Content-Type": "application/json"
          },
          success: (res) => {
              if (res.statusCode == 401) {
                  uni.setStorageSync('user', null);
              }
              if (typeof cb == 'function') {
                  cb(res.data, '');
              }
              uni.hideNavigationBarLoading();
              if (res.statusCode == '200') {                
                wx.config({
                  debug:false,
                  appId:config.APPID,
                  timestamp:res.data.data.timestamp,
                  nonceStr:res.data.data.nonceStr,
                  signature:res.data.data.signature,					
                  jsApiList
                });
                wx.ready(() => {
                    var tempParam = {
                      title: goods.productTitle,
                      desc: goods.productDesc,
                      link: curUrl,
                      imgUrl: goods.productPic?goods.productPic:'http://jkhmzw.shudingkj.com/static/images/logo.jpg',
                      success: (res) => {
                        console.log(res) 
                      },
                      cancel: function (res) {
                        console.log('分享失败', res)
                      },
                    }
                    if(wx.updateAppMessageShareData) {
                      wx.updateAppMessageShareData(tempParam);                  
                    } else {
                      wx.onMenuShareAppMessage(tempParam);
                    }
                });
                wx.ready(() => {
                    var tempParam = {
                      title: goods.productTitle,
                      desc: goods.productDesc,
                      link: curUrl,
                      imgUrl: goods.productPic?goods.productPic:'http://jkhmzw.shudingkj.com/static/images/logo.jpg',
                      success: (res) => {
                        console.log(res) 
                      },
                      cancel: function (res) {
                        console.log('分享失败', res)
                      },
                    }
                    if(wx.updateTimelineShareData) {
                      wx.updateTimelineShareData(tempParam);
                    } else {
                      wx.onMenuShareAppMessage(tempParam);
                    }
                });
                wx.error(function(res){
                  console.log(res.errMsg);
                })
                // 判断客户端是否支持指定js的接口
                wx.checkJsApi({
                  jsApiList,
                  success: function (res) {	       		
                    console.log('判断客户端支持js接口', res)
                  },
                })
              }
          },
          fail: (err) => {
              if (typeof cb == 'function') {
                  cb(null, err.errMsg);
              }
              uni.hideNavigationBarLoading();
          }
        })        
      }
  }
};
</script>
<style lang="scss">
@import './index.scss';
</style>
